package com.it.you.base.bigdecimal;

import com.it.you.pojo.ItemInfo;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;

public class BigDecimalTest4 {
    public static void main(String[] args) {
        BigDecimal decimal = new BigDecimal("3.446");
        String price = BigDecimalUtils.stripTrailingZeros(decimal, 2, RoundingMode.HALF_UP);
        System.out.println(decimal + " 保留2位小数：" + price);

        BigDecimal decimal1 = new BigDecimal("3.4");
        String price1 = BigDecimalUtils.stripTrailingZeros(decimal1, 2, RoundingMode.HALF_UP);
        System.out.println(decimal1 + " 保留2位小数&末尾去零：" + price1);
        BigDecimal price2 = decimal1.setScale(2, RoundingMode.HALF_UP);
        System.out.println(decimal1 + " 保留2位小数：" + price2);

        List<ItemInfo> list = new ArrayList<>();
        list.add(new ItemInfo(new BigDecimal("3.99"), new BigDecimal("5.00"), 2, "电脑"));
        list.add(new ItemInfo(new BigDecimal("1.99"), new BigDecimal("3.00"), 1, "手机"));
        list.add(new ItemInfo(new BigDecimal("3.99"), new BigDecimal("5.00"), 1, "电脑"));
        list.add(new ItemInfo(new BigDecimal("0.99"), new BigDecimal("2.00"), 1, "充电线"));
        list.add(new ItemInfo(new BigDecimal("0.99"), new BigDecimal("2.00"), 1, "充电线"));
        list.add(new ItemInfo(new BigDecimal("1.99"), new BigDecimal("3.00"), 1, "手机"));

        //按照名称分组后，统计同一名称的累计金额
        Map<String, BigDecimal> map = list.stream().collect(Collectors.groupingBy(ItemInfo::getName,
                Collectors.reducing(BigDecimal.ZERO, ItemInfo::getMemberPrice, BigDecimal::add)));
        System.out.println(map);

        //按照名称分组后，统计同一组内的的所有字段累计金额
        Map<String, ItemInfo> collect = list.stream().collect(Collectors.groupingBy(ItemInfo::getName,
                Collector.of(() -> new ItemInfo(BigDecimal.ZERO, BigDecimal.ZERO, 0, null),
                        (o, p) -> {
                            if (o.getName() == null) {
                                o.setName(p.getName());
                            }
                            o.setMemberPrice(o.getMemberPrice().add(p.getMemberPrice()));
                            o.setActivityPrice(o.getActivityPrice().add(p.getActivityPrice()));
                            o.setCount(o.getCount()+p.getCount());
//                            o.setCount(o.getCount() == null ? 1 : o.getCount() + 1);
                        }, (o, p) -> p)));
        System.out.println(collect);

    }
}
